// $_FILEHEADER_BEGIN ***************************
// 版权声明:Timer
// Copyright © 2015 - Timer All Rights Reserved
// 文件名称: VerifyPhoneViewController.m
// 创建日期: 15/12/6
// 创 建 人: 甄鑫
// 文件说明: <#content#>
// $_FILEHEADER_END ******************************


#import "VerifyPhoneViewController.h"
#import "NavHelper.h"
#import "NavStatus.h"
#import "VerifyPhoneSceneModel.h"
#import "AlertDialogHelper.h"
#import "MeStatus.h"
#import <CloudPushSDK/CloudPushSDK.h>
#import <ALBBSDK/ALBBSDK.h>

@interface VerifyPhoneViewController (){
    NSTimer *_timer;
    int _cnt;
}
@property (weak, nonatomic) IBOutlet UIImageView *mpPhoneLogoImage;
@property (weak, nonatomic) IBOutlet UITextField *mpPhoneTextField;
@property (weak, nonatomic) IBOutlet UIImageView *mpCodeLogoImage;
@property (weak, nonatomic) IBOutlet UITextField *mpCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *mpCodeSendBtn;
@property (weak, nonatomic) IBOutlet UIButton *mpSendVerifyCodeBtn;
@property (weak, nonatomic) IBOutlet UILabel *mpVerifyTextAlertLabel;
@property (strong, nonatomic) VerifyPhoneSceneModel * verifySceneModel;
@end

@implementation VerifyPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.navBar setTitle:@"验证手机"];
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_BLUE];
    [_mpPhoneTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    _mpCodeSendBtn.enabled = NO;
    [_mpCodeSendBtn setImage:[UIImage imageNamed:@"grayButtonFetch"] forState:UIControlStateNormal];
    _verifySceneModel = [VerifyPhoneSceneModel SceneModel];
    @weakify(self);
    //获取验证码
    [[self.mpCodeSendBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x)
    {
        NSString *phone = _mpPhoneTextField.text;
        if ([phone stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]==0||phone.length<11||![phone isMobile]) {
            [AlertDialogHelper showToast:@"手机号不正确"];
            return ;
        }
        if (self.mpCodeSendBtn.selected == YES) {
            return;
        }else{
            self.mpCodeSendBtn.selected = YES;
        }
        @strongify(self);
        [self.verifySceneModel sendVerifyPhoneNum:[_mpPhoneTextField.text integerValue] cb:^(VERIFY_PHONE_STATUS status, id recvData)
         {
             if ([recvData objectForKey:@"result"]) {
                 if ([[recvData objectForKey:@"rtype"] integerValue]==0) {
                     ITLogSP(@"发送成功%@",[recvData objectForKey:@"errormsg"]);
                     self.mpCodeSendBtn.selected = YES;
                     _cnt = 60;
                     _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerRun:) userInfo:nil repeats:YES];
                     [_timer fireDate];
                 }else{
                     self.mpCodeSendBtn.selected = NO;
                     NSString * errorMsg = [recvData objectForKey:@"errormsg"];
                     [AlertDialogHelper showToast:errorMsg];
                     return ;
                 }
             }else{
                 self.mpCodeSendBtn.selected = NO;
                 NSString * errorMsg = [recvData objectForKey:@"errormsg"];
                 [AlertDialogHelper showToast:errorMsg];
                 return ;
             }
        }];
    }];
    
    
    //验证验证码 并绑定
    [[self.mpSendVerifyCodeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        if ([_mpPhoneTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]==0||_mpPhoneTextField.text.length<11||![_mpPhoneTextField.text isMobile]) {
            [AlertDialogHelper showToast:@"手机号不正确"];
            return ;
        }
        if (_mpCodeTextField.text.length==0) {
            [AlertDialogHelper showToast:@"请输入验证码"];
            return ;
        }
        @strongify(self);
        [self.verifySceneModel sendCode:[self.mpCodeTextField.text copy] AndPhoneNum:[self.mpPhoneTextField.text copy] ToVerifyPhoneCb:^(VERIFY_PHONE_STATUS status, id recvData) {
            if ([[NSString stringWithFormat:@"%@",[recvData objectForKey:@"result"]] integerValue]==1) {
                
                ITLogSP(@"登陆成功,保存loginKey,已经验证手机号直接返回");
                // 直接保存登录key
                [CloudPushSDK unbindAccount:[recvData objectForKey:@"outid"] withCallback:^(BOOL success) {
                    [CloudPushSDK bindAccount:[recvData objectForKey:@"outid"] withCallback:^(BOOL success) {
                        if (success) {
                            ITLog(@"绑定成功");
                        }
                    }];
                    
                }];
                _mpPhoneTextField.text = @"";
                _mpCodeTextField.text = @"";
                [self.view endEditing:YES];
                [[MeStatus sharedInstance] saveVerifyPhoneKey:@"YES"];
                //[AlertDialogHelper showToast:@"登录成功"];
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
                    
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_LoginSuccess object:nil];
            }else{
                NSString * errorMsg = [recvData objectForKey:@"errormsg"];
                [AlertDialogHelper showToast:errorMsg];
                return ;
            }
        }];
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _mpPhoneTextField.text = @"";
    _mpCodeTextField.text = @"";
    [self.view endEditing:YES];
}
#pragma mark - action
- (void)timerRun:(NSTimer *)sender{
    _cnt--;
    if (_cnt == 0) {
        [sender invalidate];
        self.mpCodeSendBtn.selected = NO;
        self.mpCodeTextField.placeholder = @"验证码";
        return;
    }
    self.mpCodeTextField.placeholder = [NSString stringWithFormat:@"%d秒后重新获取",_cnt];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
//    [[NavStatus sharedInstance]setCurWindowType:WINDOW_TYPE_NORMAL];
}

- (void)leftButtonClick{
    _mpPhoneTextField.text = @"";
    _mpCodeTextField.text = @"";
    [self.view endEditing:YES];
   [self dismissViewControllerAnimated:YES completion:^{
       
   }];
    
}

- (void)textFieldEditChanged:(UITextField *)textField{
    if (textField.text.length>0) {
        _mpCodeSendBtn.enabled = YES;
        [_mpCodeSendBtn setImage:[UIImage imageNamed:@"fetchNumButtonDefault"] forState:UIControlStateNormal];
    }else{
        _mpCodeSendBtn.enabled = NO;
        [_mpCodeSendBtn setImage:[UIImage imageNamed:@"grayButtonFetch"] forState:UIControlStateNormal];
    }
}
@end
